package com.zmn.oms.business.impl.order;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.zmn.base.common.data.common.dro.area.AreaDRO;
import com.zmn.base.common.data.common.dro.brand.BrandDRO;
import com.zmn.base.common.data.common.dro.tags.TagsDRO;
import com.zmn.base.common.data.dubbo.interfaces.area.AreaListRemoteService;
import com.zmn.base.common.data.dubbo.interfaces.brand.BrandListRemoteService;
import com.zmn.base.pilot.common.dto.pilot.PilotCheckQuery;
import com.zmn.base.pilot.common.enums.PilotTypeEnum;
import com.zmn.base.pilot.dubbo.interfaces.pilot.PilotRemoteService;
import com.zmn.base.price.common.dto.fixed.FixedErpProductDRO;
import com.zmn.base.price.common.dto.fixed.FixedErpProductQuery2;
import com.zmn.base.price.common.dto.item.ItemCellDRO;
import com.zmn.base.price.common.dto.item.ItemDRO;
import com.zmn.base.price.common.dto.item.ItemPriceQuery;
import com.zmn.base.price.common.dto.item.ItemSimpleDRO;
import com.zmn.base.price.dubbo.interfaces.calculate.FixedFlowRemoteService;
import com.zmn.base.price.dubbo.interfaces.calculate.ItemPriceRemoteService;
import com.zmn.base.product.common.consts.BaseProductConsts;
import com.zmn.base.product.common.dto.categ.CategProductGroupDRO;
import com.zmn.base.product.common.dto.product.ProductBaseQuery;
import com.zmn.base.product.common.dto.product.ec.DefaultEcProductQuery;
import com.zmn.base.product.common.dto.product.ec.ProductBaseDRO;
import com.zmn.base.product.common.query.categ.CategProductGroupQuery;
import com.zmn.base.product.dubbo.interfaces.categ.serv.CategServProductListRemoteService;
import com.zmn.base.product.dubbo.interfaces.product.foreign.ProductForeignListRemoteService;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dictionary.GlobalDict;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.math.MathUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.consts.GateTypeConsts;
import com.zmn.dms.common.dto.coup.dro.coupon.CoupOnBaseDRO;
import com.zmn.dms.common.enums.coup.CoupTypeEnums;
import com.zmn.dms.dubbo.interfaces.coup.coupon.CoupOnceCardRemoteService;
import com.zmn.oms.business.interfaces.base.BaseCodeService;
import com.zmn.dms.dubbo.utils.DubboConsts;
import com.zmn.oms.business.interfaces.operation.OrderOperationBService;
import com.zmn.oms.business.interfaces.order.OrderBService;
import com.zmn.oms.business.interfaces.product.OrderProductExtendBService;
import com.zmn.oms.business.interfaces.remark.OrderRemarkBService;
import com.zmn.oms.business.interfaces.serviceitem.OrderServiceItemBService;
import com.zmn.oms.business.interfaces.servtype.ServItemBService;
import com.zmn.oms.business.interfaces.work.OrderWorkBService;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.constant.OrderStatusConsts;
import com.zmn.oms.common.constant.OrderTagConsts;
import com.zmn.oms.common.dto.MapDTO;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.common.utils.FilterUtil;
import com.zmn.oms.model.bo.order.OrderBO;
import com.zmn.oms.model.dto.order.OmsProductDTO;
import com.zmn.oms.model.dto.order.OrderDTO;
import com.zmn.oms.model.dto.order.OrderUserDetailDTO;
import com.zmn.oms.model.dto.order.ServProductDTO;
import com.zmn.oms.model.dto.product.OrderProductDTO;
import com.zmn.oms.model.dto.tag.OrderTagDTO;
import com.zmn.oms.model.dto.tag.OrderTagDelDTO;
import com.zmn.oms.model.dto.work.modify.*;
import com.zmn.oms.model.entity.activity.OrderActivity;
import com.zmn.oms.model.entity.comment.OrderComment;
import com.zmn.oms.model.entity.conf.ordertag.ConfOrderTag;
import com.zmn.oms.model.entity.conf.ordertag.ConfOrderTagQuery;
import com.zmn.oms.model.entity.detail.OrderDetail;
import com.zmn.oms.model.entity.discount.OrderDiscount;
import com.zmn.oms.model.entity.factory.OrderFactory;
import com.zmn.oms.model.entity.operation.OrderOperation;
import com.zmn.oms.model.entity.order.Order;
import com.zmn.oms.model.entity.order.OrderExtend;
import com.zmn.oms.model.entity.orderfinalpricequotation.OrderFinalPriceQuotation;
import com.zmn.oms.model.entity.outermap.OrderOuterMap;
import com.zmn.oms.model.entity.product.OrderProduct;
import com.zmn.oms.model.entity.product.OrderProductExtend;
import com.zmn.oms.model.entity.serviceitem.OrderServiceItem;
import com.zmn.oms.model.entity.serviceitem.OrderServiceItemCell;
import com.zmn.oms.model.entity.shop.OrderShop;
import com.zmn.oms.model.entity.tag.OrderTag;
import com.zmn.oms.model.entity.warranty.OrderWarranty;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.services.interfaces.activity.OrderActivityService;
import com.zmn.oms.services.interfaces.comment.OrderCommentService;
import com.zmn.oms.services.interfaces.conf.ordertag.ConfOrderTagService;
import com.zmn.oms.services.interfaces.detail.OrderDetailService;
import com.zmn.oms.services.interfaces.factory.OrderFactoryService;
import com.zmn.oms.services.interfaces.member.OrderMemberService;
import com.zmn.oms.services.interfaces.order.OrderExtendService;
import com.zmn.oms.services.interfaces.order.OrderService;
import com.zmn.oms.services.interfaces.orderpaydiscount.OrderPayDiscountService;
import com.zmn.oms.services.interfaces.outermap.OrderOuterMapService;
import com.zmn.oms.services.interfaces.serviceitem.OrderServiceItemService;
import com.zmn.oms.services.interfaces.shop.OrderExternalShopService;
import com.zmn.oms.services.interfaces.shop.OrderShopService;
import com.zmn.oms.services.interfaces.tag.OrderTagService;
import com.zmn.oms.services.interfaces.warranty.OrderWarrantyService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.pay.common.constant.PayConsts;
import com.zmn.ums.common.constant.UserConsts;
import com.zmn.ums.dubbo.interfaces.user.UserTagInfoListRemoteService;
import com.zmn.uuc.common.dro.user.UserAddrDRO;
import com.zmn.uuc.common.dro.user.UserBaseDRO;
import com.zmn.uuc.common.dro.user.UserDetailDRO;
import com.zmn.uuc.dubbo.interfaces.user.UserAddrListRemoteService;
import com.zmn.uuc.dubbo.interfaces.user.UserRegisterRemoteService;
import com.zmn.vas.common.dro.member.MemberDRO;
import com.zmn.vas.dubbo.interfaces.member.MemberListRemoteService;
import com.zmn.vas.dubbo.interfaces.order.VasOrderListRemoteService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * 类描述：订单
 *
 * @author liuying
 * @date 2018/11/07 19:31
 */
@Service
public class OrderBServiceImpl implements OrderBService {

    private Logger logger = LoggerFactory.getLogger(OrderBServiceImpl.class);
    @Reference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION , check = false)
    private AreaListRemoteService areaListRemoteService;
    @Reference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION , check = false)
    private BrandListRemoteService brandListRemoteService;
    @Reference(version = com.zmn.uuc.common.constant.DubboConsts.INTERFACE_VERSION, check = false)
    private UserRegisterRemoteService userRegisterRemoteService;
    @Reference(version = com.zmn.uuc.common.constant.DubboConsts.INTERFACE_VERSION, check = false)
    private com.zmn.uuc.dubbo.interfaces.user.UserListRemoteService userListRemoteService;
    @Reference(version = com.zmn.vas.dubbo.consts.VasDubboConsts.INTERFACE_VERSION, check = false)
    private MemberListRemoteService memberListRemoteService;
    @Reference(version = com.zmn.uuc.common.constant.DubboConsts.INTERFACE_VERSION, check = false)
    private UserAddrListRemoteService userAddrListRemoteService;
    @Reference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION , check = false)
    private ProductForeignListRemoteService productForeignListRemoteService;
    @Reference(version = com.zmn.vas.dubbo.consts.VasDubboConsts.INTERFACE_VERSION, check = false)
    private VasOrderListRemoteService vasOrderListRemoteService;
    @Reference(version = com.zmn.vas.dubbo.consts.VasDubboConsts.INTERFACE_VERSION, check = false)
    private CategServProductListRemoteService categServProductListRemoteService;
    @Reference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION , check = false)
    private PilotRemoteService pilotRemoteService;
    @org.apache.dubbo.config.annotation.Reference(version = com.zmn.ums.dubbo.utils.DubboConsts.INTERFACE_VERSION, check = false, timeout = 2000)
    private UserTagInfoListRemoteService userTagInfoListRemoteService;
    @Reference(version = DubboConsts.INTERFACE_VERSION, check = false)
    private CoupOnceCardRemoteService coupOnceCardRemoteService;
    @Reference(version = DubboConsts.INTERFACE_VERSION, check = false)
    private FixedFlowRemoteService fixedFlowRemoteService;
    @Reference(version = DubboConsts.INTERFACE_VERSION, check = false)
    private ItemPriceRemoteService itemPriceRemoteService;

    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderWorkService orderWorkService;
    @Autowired
    private OrderWorkBService orderWorkBService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private OrderWarrantyService orderWarrantyService;
    @Autowired
    private OrderCommentService orderCommentService;
    @Autowired
    private OrderOuterMapService orderOuterMapService;
    @Autowired
    private OrderFactoryService orderFactoryService;
    @Autowired
    private OrderProductExtendBService orderProductExtendBService;
    @Autowired
    private OrderShopService orderShopService;
    @Autowired
    private OrderServiceItemService orderServiceItemService;
    @Autowired
    private OrderOperationBService orderOperationBService;
    @Autowired
    private OrderMemberService orderMemberService;
    @Autowired
    private OrderServiceItemBService orderServiceItemBService;
    @Autowired
    private OrderExtendService orderExtendService;
    @Autowired
    private OrderTagService orderTagService;
    @Autowired
    private OrderActivityService orderActivityService;
    @Autowired
    private ConfOrderTagService confOrderTagService;
    @Autowired
    private ServItemBService servItemBService;
    @Autowired
    private BaseCodeService baseCodeService;
    @Autowired
    private OrderPayDiscountService orderPayDiscountService;
    @Autowired
    private OrderRemarkBService orderRemarkBService;
    @Autowired
    private OrderExternalShopService orderExternalShopService;

    /**
     * 产品处理
     * @param orderProductDTO
     * @return
     */
    @Override
    public void processBeforeOrderProduct(OrderProductDTO orderProductDTO) {
        // 页面传了前端产品标记，分别设置到前后端产品字段
        if (!NumberUtil.isNullOrZero(orderProductDTO.getProductShowType())) {
            if (Objects.equals(orderProductDTO.getProductShowType(), BaseProductConsts.EC_SHOW_TYPE)) {
                orderProductDTO.setProductId(0);
            } else {
                orderProductDTO.setShowProductId(0);
            }
        }

        // 仅有前端产品
        boolean onlyShowProductId = !NumberUtil.isNullOrZero(orderProductDTO.getShowProductId()) && NumberUtil.isNullOrZero(orderProductDTO.getProductId());
        if (onlyShowProductId) {
            // 传递的前端产品，可能是后台产品
            ProductBaseQuery productDIO = new ProductBaseQuery();
            productDIO.setProductId(orderProductDTO.getShowProductId());
            ResponseDTO<List<ProductBaseDRO>> productRemote = productForeignListRemoteService.listBaseDROByQuery(productDIO);
            if (CollectionUtil.isNotNullOrEmpty(productRemote.getData()) && Objects.equals(BaseProductConsts.ERP_SHOW_TYPE, productRemote.getData().get(0).getShowType())) {
                logger.info("传递前台产品[{}]，实际为后台产品", orderProductDTO.getShowProductId());
                orderProductDTO.setProductId(orderProductDTO.getShowProductId());
                orderProductDTO.setShowProductId(0);
            }
        }
    }

    @Override
    public void processOrder(OrderDTO orderDTO) throws OmsBaseException {
        Order order = orderDTO.getOrder();
        OrderWork orderWork = orderDTO.getOrderWork();

        // 默认新单
        order.setType(Optional.ofNullable(order.getType()).orElse(OrderConsts.ORDER_TYPE_NEW));
        order.setReceiveEntranceId(orderWork.getReceiveEntranceId());
        // 订单处理
        this.processOrderUserAndAddress(orderDTO);

        // 处理要客信息和订单标签
        try {
            this.processVVIP(orderDTO);
        } catch (Exception ex){
            logger.error("processOrder.processVVIP 处理异常：{}", ex);
        }
        try {
            this.processOrderTag(orderDTO);
        } catch (Exception ex){
            logger.error("processOrder.processOrderTag 处理异常：{}", ex);
        }

        // 订单产品处理
        this.processOrderProductList(orderDTO);

        // 订单详情处理
        this.processOrderDetail(orderDTO);

        // 订单扩展数据处理
        this.processOrderExtend(orderDTO);
    }

    /** @Author wangyanci
     * @Description 处理下单默认服务项
     * @Date 11:23 2022/4/13
     **/
    @Override
    public void processPlaceAnOrderDefaultServItem(OrderDTO orderDTO) throws OmsBaseException {
        OrderWork orderWork = orderDTO.getOrderWork();
        OrderProduct orderProduct = orderDTO.getOrderProductList().get(0);
        Integer number = orderProduct.getNumber();

//        // 如果是提前报价订单
//        OrderFinalPriceQuotation quotation = orderDTO.getOrderFinalPriceQuotation();
//        if (Objects.nonNull(quotation) && NumberUtil.isNotNullOrZero(quotation.getPhenId())) {
//            try {
//                // 先比较，是否有传过来的服务项，并且与报价信息带的是同一服务项 （后台下单会带）
//                if (CollectionUtil.isNotNullOrEmpty(orderDTO.getOrderServiceItemList())) {
//                    // 带过来服务项，直接使用
//                    return;
//                }
//                // 没有带过来，只带了故障现象过来
//                OrderServiceItem serviceItem = this.getServiceItemWithPhenId(orderDTO);
//                if (Objects.isNull(serviceItem)) {
//                    return;
//                }
//
//                // 设置订单金额
//                int price = Optional.ofNullable(serviceItem.getItemPrice()).orElse(0);
//                orderProduct.setPrice(price);
//                orderWork.setOriginalAmount(price * orderProduct.getNumber());
//                orderDTO.setOrderServiceItemList(Lists.newArrayList(serviceItem));
//            } catch (Exception e) {
//                logger.error("处理一口价提前报价信息失败：{}", e.getMessage());
//            }
//
//        } else
        if (!CollectionUtils.isEmpty(orderDTO.getOriginOrderServiceItemList())) {
            // 如果前端传递了故障项，且当前订单满足计价器类型，使用前端的传递的故障项

            int amount = orderDTO.getOriginOrderServiceItemList().stream().mapToInt(item -> {
                int price = Optional.ofNullable(item.getItemPrice()).orElse(0);
                int itemNumber = Optional.ofNullable(item.getNumber()).orElse(1);
                return price * itemNumber;
            }).sum();

            // 设置订单金额
            orderProduct.setPrice(amount);
            orderWork.setOriginalAmount(amount * number);
            orderDTO.setOrderServiceItemList(orderDTO.getOriginOrderServiceItemList());
        }
        else {
            // 一口价不塞默认服务项
            if (Objects.equals(orderWork.getFinalPrice(), GlobalConsts.YES)) {
                return;
            }
            // 前台产品没有对应后台产品
            if (NumberUtil.isNullOrZero(orderWork.getProductId())) {
                logger.info("#order#serviceitem orderId:{} 前台产品没有找到对应的后台产品。 前台产品ID：{}",
                        orderWork.getOrderId(), orderWork.getShowProductId());
                return;
            }
            // 查询默认故障服务项
            BackProductPriceQueryDTO serviceItemQueryDTO = BackProductPriceQueryDTO.builder()
                    .platWork(orderWork.getPlatWork())
                    .channelId(orderWork.getChannelId())
                    .cityId(orderWork.getCityId())
                    .productId(orderWork.getProductId())
                    .brandId(orderProduct.getBrandId())
                    .bizType(orderWork.getBizType())
                    .cityId(orderWork.getCityId())
                    .build();
            BackProductPriceResultDTO defaultServiceItemResultDTO = servItemBService.queryBackProductPrice(serviceItemQueryDTO);
            if (Objects.isNull(defaultServiceItemResultDTO) || Objects.isNull(defaultServiceItemResultDTO.getDefaultServiceItem())) {
                return;
            }

            ServiceItemResultDTO defaultServiceItem = defaultServiceItemResultDTO.getDefaultServiceItem();
            // 处理内部结算价
            Integer internalPrice = Optional.ofNullable(defaultServiceItem.getInternalSettlementPrice()).orElse(defaultServiceItem.getPrice());
            Integer internalSettlementPrice = orderServiceItemBService.handleSettlementPrice(orderWork.getPlatWork(), orderWork.getChannelId(), orderWork.getBizType(), internalPrice, defaultServiceItem.getPrice());

            // 构建默认服务项
            OrderServiceItem orderServiceItem = new OrderServiceItem();
            orderServiceItem.setOrderId(orderWork.getOrderId());
            orderServiceItem.setProductId(orderProduct.getProductId());
            orderServiceItem.setProductName(orderProduct.getProductName());
            orderServiceItem.setServItemId(defaultServiceItem.getItemId());
            orderServiceItem.setServItemName(defaultServiceItem.getItemName());
            orderServiceItem.setServItemGroupId(defaultServiceItem.getItemCategId());
            orderServiceItem.setServItemGroupName(defaultServiceItem.getItemCategName());
            orderServiceItem.setServItemCategId(defaultServiceItem.getItemCategId());
            orderServiceItem.setNumber(1);
            orderServiceItem.setItemPrice(defaultServiceItem.getPrice());
            orderServiceItem.setTotalPrice(defaultServiceItem.getPrice());
            orderServiceItem.setInternalSettlementPrice(internalSettlementPrice);
            orderServiceItem.setInternalTotalPrice(internalSettlementPrice);
            orderServiceItem.setExternalSettlementPrice(Optional.ofNullable(defaultServiceItem.getExternalSettlementPrice()).orElse(defaultServiceItem.getPrice()));
            orderServiceItem.setExternalTotalPrice(Optional.ofNullable(defaultServiceItem.getExternalSettlementPrice()).orElse(defaultServiceItem.getPrice()));
            // 故障项明细
            if (CollectionUtil.isNotNullOrEmpty(defaultServiceItem.getDetailResultDTOList())) {
                List<OrderServiceItemCell> itemCellList = new ArrayList<>(defaultServiceItem.getDetailResultDTOList().size());
                for (ServiceItemDetailResultDTO itemCell : defaultServiceItem.getDetailResultDTOList()) {
                    OrderServiceItemCell cell = new OrderServiceItemCell();
                    cell.setItemCellId(itemCell.getItemCellId());
                    cell.setItemCellName(itemCell.getItemCellName());
                    cell.setCellPrice(itemCell.getCellPrice());
                    cell.setSort(itemCell.getSort());
                    itemCellList.add(cell);
                }
                orderServiceItem.setItemDetailList(itemCellList);
            }

            int price = Optional.ofNullable(defaultServiceItem.getPrice()).orElse(0);
            orderProduct.setPrice(price);
            orderWork.setOriginalAmount(price * orderProduct.getNumber());
            orderDTO.setOrderServiceItemList(Lists.newArrayList(orderServiceItem));
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderBO updateOrder(OrderDTO orderDTO) {
        Order order = orderDTO.getOrder();
        OrderDetail orderDetail = orderDTO.getOrderDetail();
        List<OrderProduct> orderProductList = orderDTO.getOrderProductList();
        OrderWork orderWork = orderDTO.getOrderWork();

        // 保存订单数据
        orderService.updateOrder(orderDTO);

        // 保存工单
        orderWorkBService.updateOrderWork(orderWork);

        // 保存厂商单信息
        OrderFactory orderFactory = orderDTO.getOrderFactory();
        if (orderFactory != null) {
            orderFactory.setFcOrderId(orderWork.getOrderId());
            orderFactoryService.updateOrderFactoryByKey(orderDTO.getOrderFactory());
        }

        // 保存下单备注信息
        if (Objects.nonNull(orderDTO.getCommonRemark())) {
            orderRemarkBService.insertOrderRemark(orderDTO.getCommonRemark(), OrderConsts.ORDER_REMARK_TYPE_INPUT);
        }

        // merge订单外部店铺
        orderExternalShopService.mergeByOrderIdAndWorkId(orderWork.getOrderId(), orderWork.getWorkId(), orderDTO.getOrderExternalShop());

        OrderBO orderBO = new OrderBO();
        orderBO.setOrder(order);
        orderBO.setOrderDetail(orderDetail);
        orderBO.setOrderProductList(orderProductList);
        orderBO.setOrderWork(orderWork);
        return orderBO;
    }

    /**
     * 处理订单服务项
     * @param orderDTO
     */
    private void processOrderServiceItem(OrderDTO orderDTO) {

        Order order = orderDTO.getOrder();
        OrderWork orderWork = orderDTO.getOrderWork();

        // 订单产品服务项
        List<OrderServiceItem> orderServiceItemList = orderDTO.getOrderServiceItemList();
        if (CollectionUtils.isEmpty(orderServiceItemList)) {
            return;
        }

        // 生成产品扩展表
        List<OrderProductExtend> productExtendList = orderProductExtendBService.getOrderProductExtend(order.getOrderId());
        if (CollectionUtils.isEmpty(productExtendList)) {
            logger.error("#order#insert 产品扩展表为空 orderId:{}", order.getOrderId());
            return;
        }

        Integer servItemType = orderWork.getServItemType();
        List<OrderServiceItem> serviceItemList = null;

        if (servItemBService.isQuotationType(servItemType)) {
            // 故障服务项订单中只能有一个产品，即只有一个产品扩展项
            if (!Objects.equals(productExtendList.size(), 1)) {
                logger.error("#order#insert 故障服务项订单中产品扩展表数量超过1个，保存故障服务项失败 productExtendList:{}；orderServiceItemList:{}",
                        JSON.toJSONString(productExtendList), JSON.toJSONString(orderServiceItemList));
                return;
            }
            serviceItemList = new LinkedList<>();
            OrderProductExtend orderProductExtend = productExtendList.get(0);

            if (serviceItemList != null) {
                for (OrderServiceItem item : orderServiceItemList) {
                    item.setOrderId(order.getOrderId());
                    item.setProExtId(orderProductExtend.getProExtId());
                    item.setProductId(orderProductExtend.getProductId());
                    item.setProductName(orderProductExtend.getProductName());
                    item.setTotalPrice(item.getItemPrice() * item.getNumber());
                    item.setExternalTotalPrice(Optional.ofNullable(item.getExternalSettlementPrice()).orElse(0) * item.getNumber());
                    item.setInternalTotalPrice(Optional.ofNullable(item.getInternalSettlementPrice()).orElse(0) * item.getNumber());
                    serviceItemList.add(item);
                }
            }
        }
        else {
            // 校验服务项数量和产品数量是否一致
            if (!Objects.equals(productExtendList.size(), orderServiceItemList.size())) {
                logger.error("#order#insert 产品扩展表数量 和 服务项数量不一致 productExtendList:{} orderServiceItemList:{}", JSON.toJSONString(productExtendList), JSON.toJSONString(orderServiceItemList));
                return;
            }

            serviceItemList = Lists.newArrayListWithCapacity(orderServiceItemList.size());

            for (int i = 0; i < orderServiceItemList.size(); i++) {
                OrderServiceItem orderServiceItem = orderServiceItemList.get(i);
                OrderProductExtend orderProductExtend = productExtendList.get(i);
                orderServiceItem.setOrderId(order.getOrderId());
                orderServiceItem.setProExtId(orderProductExtend.getProExtId());
                orderServiceItem.setProductId(orderProductExtend.getProductId());
                orderServiceItem.setProductName(orderProductExtend.getProductName());
                orderServiceItem.setTotalPrice(orderServiceItem.getItemPrice() * orderServiceItem.getNumber());
                orderServiceItem.setExternalTotalPrice(Optional.ofNullable(orderServiceItem.getExternalSettlementPrice()).orElse(0) * orderServiceItem.getNumber());
                orderServiceItem.setInternalTotalPrice(Optional.ofNullable(orderServiceItem.getInternalSettlementPrice()).orElse(0) * orderServiceItem.getNumber());
                OrderServiceItem serviceItem = JSON.parseObject(JSON.toJSONString(orderServiceItem), OrderServiceItem.class);
                serviceItemList.add(serviceItem);
            }
        }

        // 阶梯价服务项目处理
        orderServiceItemBService.handleItemsTieredPrice(serviceItemList);

        orderServiceItemService.insertAll(serviceItemList);

        // 计算原价
        int sum = orderServiceItemList.stream().flatMapToInt(e -> IntStream.of(e.getTotalPrice())).sum();
        orderWork.setOriginalAmount(sum);
    }


    /**
     * 处理啄木鸟预付
     * @param orderDTO
     */
    private void processPrepayAmount(OrderDTO orderDTO) {
        OrderWork orderWork = orderDTO.getOrderWork();
        List<OrderServiceItem> orderServiceItemList = orderDTO.getOrderServiceItemList();

        // 有服务项 & 一口价的为啄木鸟预付
        boolean haveFinalPrice = CollectionUtils.isNotEmpty(orderServiceItemList) && Objects.equals(orderDTO.getFinalPrice(), GlobalConsts.YES);
        // 需要预付金
        boolean needPrepayAmount = !NumberUtil.isNullOrZero(orderWork.getPrepayAmount());
        // 先付
        if (Objects.equals(orderDTO.getPayType(), GlobalConsts.NO) && (haveFinalPrice || needPrepayAmount)) {
            Integer prepayAmount = null;
            Integer masterAmount = null;
            if (needPrepayAmount && haveFinalPrice) {
                prepayAmount = orderWork.getPrepayAmount();
                // 有预付金的一口价，需要设置工程师收款金额
                masterAmount = MathUtil.sub(orderWork.getOriginalAmount(), Optional.ofNullable(orderWork.getDiscountAmount()).orElse(0));
                masterAmount = MathUtil.sub(masterAmount, prepayAmount);
            } else if (needPrepayAmount) {
                // 只需付预付金
                prepayAmount = orderWork.getPrepayAmount();
            } else if (haveFinalPrice) {
                // 只一口价
                prepayAmount = MathUtil.sub(orderWork.getOriginalAmount(), Optional.ofNullable(orderWork.getDiscountAmount()).orElse(0));
            }

            orderWork.setPrepayAmount(prepayAmount);
            if (Objects.equals(0, prepayAmount)) {
                orderWork.setPrepayStatus(PayConsts.PAY_STATUS_DONE);
                orderWork.setDisableDiscard(GlobalConsts.NO);
            } else {
                orderWork.setPrepayStatus(PayConsts.PAY_STATUS_ING);
                orderWork.setDisableDiscard(GlobalConsts.YES);
            }
            orderWork.setMasterAmount(masterAmount);
        }else {
            orderWork.setPrepayAmount(null);
            orderWork.setPrepayStatus(GlobalConsts.NONE);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderBO insertOrder(OrderDTO orderDTO) {

        Order order = orderDTO.getOrder();
        OrderDetail orderDetail = orderDTO.getOrderDetail();
        List<OrderProduct> orderProductList = orderDTO.getOrderProductList();
        OrderWork orderWork = orderDTO.getOrderWork();

        // 保存订单详情 订单 订单产品
        orderService.insertOrderAndProduct(orderDTO);

        // 处理订单服务项 设置订单金额
        processOrderServiceItem(orderDTO);

        // 处理工单优惠券
        processOrderDiscountCoupon(orderDTO);

        // 保存订单数据
        //orderService.insertOrderDiscount(orderDTO);

        // 处理啄木鸟预付
        logger.info("3.订单[{}]", JSON.toJSONString(orderDTO));
        processPrepayAmount(orderDTO);
        logger.info("4.订单[{}]", JSON.toJSONString(orderDTO));

		// 设置入口类型id
		Integer receiveEntranceId = orderWork.getReceiveEntranceId();
		if (!NumberUtil.isNullOrZero(receiveEntranceId)) {
			Integer gateType = Optional.ofNullable(GateTypeConsts.GATE_TYPE_MAP.get(receiveEntranceId)).orElse(0);
			if (NumberUtil.isNullOrZero(gateType)) {
				String strReceiveEntranceId = String.valueOf(receiveEntranceId);
				if (strReceiveEntranceId.length() >= 2) {
					gateType = Integer.valueOf(strReceiveEntranceId.substring(0, 2));
				}
			}
			orderWork.setReceiveEntranceType(gateType);
		}

        // 保存工单
        orderWork.setOrderId(order.getOrderId());
        orderWork.setCreater(order.getCreater());
        orderWork.setCreateTime(order.getCreateTime());

        // 退款单
        if (orderWork.getType() == OrderConsts.ORDER_TYPE_REFUND) {
            orderWork.setWorkId(null);
        } else {
            orderWork.setWorkId(order.getOrderId());
        }

        if (orderWork.getUserId() != null) {
            ResponseDTO<UserDetailDRO> userDetailDROResponseDTO = userListRemoteService.getUserDetailById(orderWork.getUserId(), false);
            logger.info("#oms#工单[{}]查询用户passId，出参={}", orderWork.getOrderId(), userDetailDROResponseDTO);
            if (userDetailDROResponseDTO.getData() != null && NumberUtil.isNotNullOrZero(userDetailDROResponseDTO.getData().getPassId())) {
                ResponseDTO<MemberDRO> memberDROResponseDTO = memberListRemoteService.getMemberById(userDetailDROResponseDTO.getData().getPassId());
                logger.info("#oms#工单[{}] 是否是会员工单，出参={}", orderWork.getOrderId(), JSON.toJSONString(memberDROResponseDTO));
                MemberDRO memberDRO = memberDROResponseDTO.getData();
                if (memberDRO != null && Objects.equals(memberDRO.getStatus(), GlobalConsts.YES)) {
                    orderWork.setSourceType(OrderConsts.ORDER_SOURCE_TYPE_MEMBER);
                }
            }
        }

        // 添加工单
        orderWorkBService.insertOrderWork(orderWork);

        // 保存对应关系
        if (StringUtils.isNotBlank(orderWork.getOuterId())) {
            OrderOuterMap orderOuterMap = new OrderOuterMap();
            orderOuterMap.setOuterId(orderWork.getOuterId());
            orderOuterMap.setChannelId(orderWork.getChannelId());
            orderOuterMap.setPlat(orderWork.getPlat());
            orderOuterMap.setOrderId(orderWork.getOrderId());
            orderOuterMap.setWorkId(orderWork.getWorkId());
            orderOuterMap.setCreateTime(orderWork.getCreateTime());
            orderOuterMapService.insertOuterMap(orderOuterMap);
        }

        // 保存厂商单信息
        OrderFactory orderFactory = orderDTO.getOrderFactory();
        if (orderFactory != null) {
            orderFactory.setFcOrderId(orderWork.getOrderId());
            orderFactoryService.insertOrderFactory(orderDTO.getOrderFactory());
        }

        // 保存店铺信息
        OrderShop orderShop = orderDTO.getOrderShop();
        if (orderShop != null) {
            orderShop.setShopOrderId(orderWork.getOrderId());
            orderShopService.insert(orderShop);
        }

        // 订单计价器操作
        boolean isAddOrderQuotation = false;
        if (servItemBService.isQuotationType(orderWork.getServItemType()) && CollectionUtil.isNotNullOrEmpty(orderDTO.getOrderServiceItemList())) {
            isAddOrderQuotation = true;
            logger.info("[{}]是下单计价", orderWork.getOrderId());
        }
        OrderOperation orderOperation = orderDTO.getOrderOperation();
        if (orderOperation != null) {
            orderOperation.setAddOrderQuotation(isAddOrderQuotation);
            orderOperation.setOrderId(orderWork.getOrderId());
            orderOperationBService.insertOrUpdateByKey(orderOperation);
        } else {
            orderOperation = new OrderOperation();
            orderOperation.setAddOrderQuotation(isAddOrderQuotation);
            orderOperation.setOrderId(orderWork.getOrderId());
            orderOperation.setQuotationId(orderDTO.getOperatorId());
            orderOperation.setQuotationName(orderDTO.getOperator());
            orderOperation.setCreater(orderDTO.getOperator());
            Date currentTime = new Date();
            orderOperation.setQuotationTime(currentTime);
            orderOperation.setCreateTime(currentTime);
            orderDTO.setOrderOperation(orderOperation);
            orderOperationBService.insertOrUpdateByKey(orderOperation);
        }

        // 保存订单扩展数据
        if (orderDTO.getOrderExtend() != null) {
            OrderExtend orderExtend = orderDTO.getOrderExtend();
            orderExtend.setExtId(orderWork.getOrderId());
            orderExtend.setCreater(orderDTO.getOperator());
            orderExtend.setCreateTime(orderWork.getCreateTime());
            orderExtendService.insertOrderExtend(orderExtend);
        }

        // 保存订单标签
        OrderTagDTO orderTagDTO = new OrderTagDTO();
        orderTagDTO.setOrderId(orderWork.getOrderId());
        orderTagDTO.setWorkId(orderWork.getWorkId());
        orderTagDTO.setOrderTagList(orderDTO.getOrderTagList());
        orderTagService.saveOrderTagList(orderTagDTO);

        // 保存工单活动
        this.saveActivity(orderWork.getOrderId(), orderDTO.getOrderActivity());

        // 保存下单支付信息
        if (CollectionUtil.isNotNullOrEmpty(orderDTO.getOrderPayDiscountList())) {
            orderDTO.getOrderPayDiscountList().forEach(orderPayDiscount -> {
                orderPayDiscount.setOrderId(orderWork.getOrderId());
                orderPayDiscount.setCreater(orderDTO.getOperator());
                orderPayDiscount.setCreateTime(orderWork.getCreateTime());
            });
            orderPayDiscountService.insertList(orderDTO.getOrderPayDiscountList());
        }

        // 保存下单常用备注
        if (Objects.nonNull(orderDTO.getCommonRemark())) {
            orderRemarkBService.insertOrderRemark(orderDTO.getCommonRemark(), OrderConsts.ORDER_REMARK_TYPE_INPUT);
        }

        OrderBO orderBO = new OrderBO();
        orderBO.setOrder(order);
        orderBO.setOrderDetail(orderDetail);
        orderBO.setOrderProductList(orderProductList);
        orderBO.setOrderWork(orderWork);
        return orderBO;
    }

    @Override
    public void processOrderAddress(OrderDTO orderDTO) throws OmsBaseException {
        // 订单地址处理
        this.processOrderUserAndAddress(orderDTO);
        // 订单详情地址处理
        this.processOrderDetail(orderDTO);
    }

    private void saveActivity(Long orderId, OrderActivity orderActivity) {
        if (Objects.isNull(orderActivity)) {
            return;
        }
        orderActivity.setOrderId(orderId);
        orderActivityService.insert(orderActivity);
    }

    /**
     * 修改地址
     *
     * @param orderDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderBO updateOrderAddress(OrderDTO orderDTO) {
        Order order = orderDTO.getOrder();
        OrderWork orderWork = orderDTO.getOrderWork();
        // 保存订单数据
        orderService.updateOrderAddress(orderDTO);
        if (BooleanUtils.isNotTrue(orderDTO.getUpdateAddress())) {
            // 保存工单
            orderWorkBService.updateOrderWorkAddress(orderWork);
        }

        OrderBO orderBO = new OrderBO();
        orderBO.setOrder(order);
        orderBO.setOrderWork(orderWork);
        return orderBO;
    }

    /**
     * 处理优惠券优惠
     * @param
     */
    private void processOrderDiscountCoupon(OrderDTO orderDTO) {

        List<OrderDiscount> orderDiscountList = orderDTO.getMosOrderDiscountList();
        OrderWork orderWork = orderDTO.getOrderWork();
        List<OrderProduct> orderProductList = orderDTO.getOrderProductList();

        // 优惠信息储存在 mosOrderDiscountList 或者 discountItemCodes

        // 判断是否次卡优惠
        // 只有一张优惠券的情况下，优惠券才可能为次卡优惠券
        // 普通优惠券

        String code = null;
        if (CollectionUtil.isNotNullOrEmpty(orderDiscountList) && orderDiscountList.size() == 1) {
            code = orderDiscountList.get(0).getItemCode();
        } else if (CollectionUtil.isNotNullOrEmpty(orderDTO.getDiscountItemCodes()) && orderDTO.getDiscountItemCodes().size() == 1) {
            code = orderDTO.getDiscountItemCodes().get(0);
        }

        if (StringUtil.isBlank(code)) {
            return;
        }

        ResponseDTO<CoupOnBaseDRO> responseDTO = coupOnceCardRemoteService.getOnceCardDetail(code);
        logger.info("下单获取优惠券信息： 入参：{}, 出参：{}", code, JSON.toJSONString(responseDTO));
        if (!responseDTO.isSuccess() || Objects.isNull(responseDTO.getData())) {
            logger.error("获取优惠券信息失败");
            return;
        }
        CoupOnBaseDRO coup = responseDTO.getData();

        // 如果是次卡优惠券
        if (Objects.equals(coup.getCoupType(), CoupTypeEnums.COUP_TYPE_TIMES.getKey())) {
            orderWork.setDiscountPrepayAmount(coup.getSalePrice());
            orderDTO.setTimesCoupCode(coup.getCouponCode());
        }

        if (CollectionUtil.isNotNullOrEmpty(orderDiscountList)) {
            OrderDiscount orderDiscount = orderDiscountList.get(0);
            orderDiscount.setSellAmount(coup.getSalePrice());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void syncOrder(Long orderId) {
        Order order = new Order();
        order.setOrderId(orderId);
        OrderWork orderWork = orderWorkService.findOrderWorkByKeySrcMaster(orderId, orderId);
        OrderDetail orderDetail = orderDetailService.findOrderDetailByKeySrcMaster(orderId);
        BeanMapper.copy(orderWork, order);
        BeanMapper.copy(orderDetail, order);
        order.setPayChannelId(orderWork.getMasterPayChannelId());

        // 是否有保修卡
        OrderWarranty orderWarranty = orderWarrantyService.findByOrderId(orderId);
        if (orderWarranty == null) {
            order.setWarrantyStatus(GlobalConsts.NO);
        } else {
            order.setWarrantyStatus(GlobalConsts.YES);
        }

        // 是否已评价
        OrderComment orderComment = orderCommentService.findCommentByKey(orderId);
        if (orderComment == null || Objects.equals(orderComment.getStatus(), GlobalConsts.NO)) {
            order.setCommentStatus(GlobalConsts.NO);
        } else {
            order.setCommentStatus(GlobalConsts.YES);
        }

        // 转换 状态 和 结果
        order.setStatus(OrderStatusConsts.getOrderStatus(orderWork.getStatus(), orderWork.getResultStatus()));
        orderService.updateSyncOrder(order);
    }

    /**
     * 处理订单用户信息和地址信息
     * @param orderDTO
     * @throws OmsBaseException
     */
    private void processOrderUserAndAddress(OrderDTO orderDTO) throws OmsBaseException {
        Order order = orderDTO.getOrder();
        OrderDetail orderDetail = orderDTO.getOrderDetail();

        // 过滤空格
        orderDetail.setTelephone(orderDetail.getTelephone().trim());
        orderDetail.setTelephone2(StringUtils.defaultString(orderDetail.getTelephone2()).trim());
        orderDetail.setTelephone3(StringUtils.defaultString(orderDetail.getTelephone3()).trim());

        /*
        String mobile = orderDetail.getTelephone();
        boolean isLoginUser = false;
        
        {// 判断是否是登录用户，以确定生成临时用户还是正式用户 lhl-2020.12.17
            // 1. 有登录电话，确定为登录用户
            Optional<String> loginPhoneOpt = Optional.ofNullable(orderDTO.getChannelLoginPhone())
                    .map(String::trim)
                    .filter(StringUtil::isMobile);
            if (isLoginUser = loginPhoneOpt.isPresent()) {
                mobile = loginPhoneOpt.get();   // 将登录手机号用作创建用户手机号
            }
            // 2. 呼叫录单，默认为登录用户
            if (!isLoginUser) {
                isLoginUser = OrderConsts.LOGIN_ENTRANCE_LIST.contains(order.getReceiveEntranceId())
                        && StringUtil.isMobile(mobile);
            }
            // 3. 特殊渠道，默认为登录用户（待优化：转去对接逻辑中确定更合理）
            if (!isLoginUser) {
                isLoginUser = OrderConsts.LOGIN_CHANNEL_LIST.contains(orderWork.getChannelId())
                        && Objects.equals(orderWork.getInputType(), OrderConsts.ORDER_INPUT_TYPE_API);
            }
        }

        // 用户处理
        this.processUserId(order, orderDetail, orderWork.getChannelId(), mobile, isLoginUser, orderDTO.getOperator(), orderDTO.getOperatorId());
        */

        order.setUserId(Optional.ofNullable(order.getUserId()).orElse((long) GlobalConsts.NONE));
        orderDetail.setUserType(Optional.ofNullable(orderDetail.getUserType()).orElse(UserConsts.USER_TYPE_ORDINARY));

        Integer sourceCityId = order.getCityId();
        if (orderDetail.getLongitude() != null && Objects.isNull(orderDetail.getCountyId())) {
            ResponseDTO<com.zmn.base.common.data.common.dro.area.AreaDRO> areaResponseDTO = areaListRemoteService.getAreaByLatAndLng(orderDetail.getLongitude(), orderDetail.getLatitude());
            com.zmn.base.common.data.common.dro.area.AreaDRO areaDRO = areaResponseDTO.getData();

            // 城市和经纬不匹配时，不处理
            if (areaDRO != null) {
                logger.info("通过经纬度获取城市数据，orderId={}, userId={}，longitude={}, latitude={}, areaDRO={}", order.getOrderId(), order.getUserId(), orderDetail.getLongitude(), orderDetail.getLatitude(), areaDRO);
                if ((sourceCityId == null || Objects.equals(sourceCityId, areaDRO.getParentId()))) {
                    if (sourceCityId == null) {
                        order.setCityId(areaDRO.getParentId());
                    }
                    order.setNaturalCityId(areaDRO.getParentId());
                    orderDetail.setCountyId(areaDRO.getAreaId());
                    orderDetail.setCountyName(areaDRO.getName());
                }
            } else {
                logger.info("通过经纬度获取城市数据失败，orderId={}, userId={}，longitude={}, latitude={}，result={}",
                        order.getOrderId(), order.getUserId(), orderDetail.getLongitude(), orderDetail.getLatitude(), JSON.toJSONString(areaResponseDTO));
            }
        }

        // 区县id不为空，取消名称为空，查出区县名称
        if (NumberUtil.isNotNullOrZero(orderDetail.getCountyId())
                && StringUtil.isBlank(orderDetail.getCountyName())) {
            ResponseDTO<com.zmn.base.common.data.common.dro.area.AreaDRO> countyAreaResponse = areaListRemoteService.getById(orderDetail.getCountyId());
            logger.info("areaListRemoteService.getById({}) 出参{}", orderDetail.getCountyId(), JSON.toJSONString(countyAreaResponse));
            if (countyAreaResponse.getData() != null) {
                orderDetail.setCountyName(countyAreaResponse.getData().getName());
            }
        }

        // 判断经纬度，判断是否在这个城市下面，如果不在这个城市，则塞城市下的第一个区，经纬度清空，标准地址塞到详细地址里
        orderDetail.setStreet(StringUtils.defaultString(orderDetail.getStreet()));
        if (orderDetail.getCountyId() == null) {
            order.setNaturalCityId(order.getCityId());
            orderDetail.setCountyId(GlobalConsts.NONE);
            orderDetail.setCountyName("");
            orderDetail.setLatitude(null);
            orderDetail.setLongitude(null);
            orderDetail.setAddress(String.format("%s %s", orderDetail.getStreet(), StringUtils.defaultString(orderDetail.getAddress())));
            orderDetail.setStreet("");
        }
    }

    /**
     * 订单详情数据处理
     *
     * @param orderDTO
     * @throws OmsBaseException
     */
    private void processOrderDetail(OrderDTO orderDTO) throws OmsBaseException {

        Order order = orderDTO.getOrder();
        OrderDetail orderDetail = orderDTO.getOrderDetail();

        // 查询城市信息
        ResponseDTO<AreaDRO> cityResponseDTO = areaListRemoteService.getById(order.getCityId());
        if (!cityResponseDTO.isSuccess() || cityResponseDTO.getData() == null) {
            throw new OmsBaseException(String.format("城市不存在，CityId=[%s]", order.getCityId()));
        }

        // 查询省份信息
        ResponseDTO<AreaDRO> provinceResponseDTO = areaListRemoteService.getById(cityResponseDTO.getData().getParentId());
        if (!provinceResponseDTO.isSuccess() || provinceResponseDTO.getData() == null) {
            throw new OmsBaseException(String.format("省份不存在，ParentId=[%s]", cityResponseDTO.getData().getParentId()));
        }

        orderDetail.setUserName(FilterUtil.replaceSpeChar(orderDetail.getUserName()));
        orderDetail.setContactName(FilterUtil.replaceSpeChar(StringUtils.defaultString(orderDetail.getContactName(), orderDetail.getUserName())));
        orderDetail.setGender(Optional.ofNullable(orderDetail.getGender()).orElse(GlobalDict.GENDER_NO));
        orderDetail.setProvinceId(provinceResponseDTO.getData().getAreaId());
        orderDetail.setProvinceName(provinceResponseDTO.getData().getName());
        orderDetail.setCityName(cityResponseDTO.getData().getName());
        orderDetail.setNaturalCityName(orderDetail.getCityName());
        orderDetail.setStreetSource(Optional.ofNullable(orderDetail.getStreetSource()).orElse(0));
        orderDetail.setStreetId(Optional.ofNullable(orderDetail.getStreetId()).orElse(0));
    }

    /**
     * 订单扩展数据处理
     *
     * @param orderDTO
     * @throws OmsBaseException
     */
    private void processOrderExtend(OrderDTO orderDTO) throws OmsBaseException {
        OrderDetail orderDetail = orderDTO.getOrderDetail();
        OrderWork orderWork = orderDTO.getOrderWork();
        OrderProduct orderProduct = orderDTO.getOrderProductList().get(0);

        // 三日无忧退
        OrderExtend orderExtend = Optional.ofNullable(orderDTO.getOrderExtend()).orElse(new OrderExtend());

        logger.info("获取当前工单是否是三日无忧退工单 入参：channelId: {}, cityId:{}, servCategId:{}, categId:{}", orderWork.getChannelId(), orderWork.getCityId(), orderWork.getServCategId(), orderProduct.getShowCategId());
        PilotCheckQuery query = new PilotCheckQuery();
        query.setCityId(orderWork.getCityId());
        query.setChannelId(orderWork.getChannelId());
        query.setServCategId(orderWork.getServCategId());
        query.setCategId(orderProduct.getShowCategId());
        query.setPilotTypeId(PilotTypeEnum.THREE_DAY_RETREAT.getId());
        ResponseDTO<Boolean> responseDTO = pilotRemoteService.checkPilotByQuery(query);
        logger.info("获取当前工单是否是三日无忧退工单 出参：{}", JSON.toJSONString(responseDTO));
        if (!responseDTO.isSuccess()) {
            logger.info("无法获取当前工单是否是三日无忧退工单，入参：channelId: {}, cityId:{}, servCategId:{}, categId:{}, 原因:{}", orderWork.getChannelId(), orderWork.getCityId(), orderWork.getServCategId(), orderProduct.getShowCategId(), responseDTO.getMessage());
        } else {
            orderExtend.setAllowRefund(responseDTO.getData() ? GlobalConsts.YES : GlobalConsts.NO);
        }
        orderDTO.setOrderExtend(orderExtend);
    }

    /**
     * 订单活动处理
     *
     * @param orderDTO
     * @throws OmsBaseException
     */
    private void processOrderActivity(OrderDTO orderDTO) throws OmsBaseException {
        OrderDetail orderDetail = orderDTO.getOrderDetail();
        OrderWork orderWork = orderDTO.getOrderWork();
        OrderProduct orderProduct = orderDTO.getOrderProductList().get(0);

        // 三日无忧退
        OrderExtend orderExtend = Optional.ofNullable(orderDTO.getOrderExtend()).orElse(new OrderExtend());

        logger.info("获取当前工单是否是三日无忧退工单 入参：channelId: {}, cityId:{}, servCategId:{}, categId:{}", orderWork.getChannelId(), orderWork.getCityId(), orderWork.getServCategId(), orderProduct.getShowCategId());
        PilotCheckQuery query = new PilotCheckQuery();
        query.setCityId(orderWork.getCityId());
        query.setChannelId(orderWork.getChannelId());
        query.setServCategId(orderWork.getServCategId());
        query.setCategId(orderProduct.getShowCategId());
        query.setPilotTypeId(PilotTypeEnum.THREE_DAY_RETREAT.getId());
        ResponseDTO<Boolean> responseDTO = pilotRemoteService.checkPilotByQuery(query);
        logger.info("获取当前工单是否是三日无忧退工单 出参：{}", JSON.toJSONString(responseDTO));
        if (!responseDTO.isSuccess()) {
            logger.info("无法获取当前工单是否是三日无忧退工单，入参：channelId: {}, cityId:{}, servCategId:{}, categId:{}, 原因:{}", orderWork.getChannelId(), orderWork.getCityId(), orderWork.getServCategId(), orderProduct.getShowCategId(), responseDTO.getMessage());
        } else {
            orderExtend.setAllowRefund(responseDTO.getData() ? GlobalConsts.YES : GlobalConsts.NO);
        }
        orderDTO.setOrderExtend(orderExtend);
    }

    /**
     * 订单产品处理
     *
     * @param orderDTO
     * @throws OmsBaseException
     */
    private void processOrderProductList(OrderDTO orderDTO) throws OmsBaseException {
        Order order = orderDTO.getOrder();
        OrderDetail orderDetail = orderDTO.getOrderDetail();
        OrderWork orderWork = orderDTO.getOrderWork();
        List<OrderProduct> orderProductList = orderDTO.getOrderProductList();

        if (CollectionUtils.isEmpty(orderProductList)) {
            return;
        }

        // 目前就一个产品
        OrderProduct orderProduct = orderProductList.get(0);
        orderProduct.setNumber(Optional.ofNullable(orderProduct.getNumber()).orElse(1));
        // 品牌为空，默认为其它品牌
        orderProduct.setBrandId(Optional.ofNullable(orderProduct.getBrandId()).orElse(1051));

        OmsProductDTO omsProductDTO = this.processProduct(orderWork, orderProduct.getShowProductId(), orderProduct.getProductId(), orderProduct.getBrandId());
        // 后端产品
        ServProductDTO product = omsProductDTO.getProduct();
        orderProduct.setCategOneId(product.getCategOneId());
        orderProduct.setCategOneName(product.getCategOneName());
        orderProduct.setCategId(product.getCategId());
        orderProduct.setCategName(product.getCategName());
        orderProduct.setProductId(product.getProductId());
        orderProduct.setProductName(product.getProductName());
        orderProduct.setProductUnit(StringUtils.defaultString(product.getProductUnit()));
        orderProduct.setTariffName(StringUtils.defaultString(product.getTariffName()));
        // 前端产品
        ServProductDTO showProduct = omsProductDTO.getShowProduct();
        orderProduct.setShowCategOneId(showProduct.getCategOneId());
        orderProduct.setShowCategOneName(showProduct.getCategOneName());
        orderProduct.setShowCategId(showProduct.getCategId());
        orderProduct.setShowCategName(showProduct.getCategName());
        orderProduct.setShowProductId(showProduct.getProductId());
        orderProduct.setShowProductName(showProduct.getProductName());
        orderProduct.setShowProductUnit(StringUtils.defaultString(showProduct.getProductUnit()));

        // 品牌信息
        if (NumberUtil.isNotNullOrZero(orderProduct.getBrandId())) {
            ResponseDTO<BrandDRO> baseBrandResponseDTO = brandListRemoteService.getById(orderProduct.getBrandId());
            BrandDRO baseBrandDRO = baseBrandResponseDTO.getData();
            if (baseBrandDRO != null) {
                orderProduct.setBrandId(baseBrandDRO.getBrandId());
                orderProduct.setBrandName(baseBrandDRO.getName());
            }
        }

        orderProduct.setBrandId(Optional.ofNullable(orderProduct.getBrandId()).orElse(GlobalConsts.NONE));
        orderProduct.setBrandName(StringUtils.defaultString(orderProduct.getBrandName()));

        // 故障信息
        List<String> faultList = Lists.newArrayList();

        if (StringUtils.isNotBlank(orderProduct.getRemark())) {
            faultList.add(orderProduct.getRemark());
        }

        if (StringUtils.isNotBlank(orderProduct.getFault())) {
            try {
                List<MapDTO> faultItemList = JSON.parseArray(orderProduct.getFault(), MapDTO.class);
                faultList.addAll(Optional.ofNullable(faultItemList).orElse(Lists.newArrayListWithCapacity(0)).stream().map(MapDTO::getMapName).collect(Collectors.toList()));
            } catch (Exception ex) {
            }
        }

        // 设置产品故障
        if (CollectionUtils.isNotEmpty(faultList)) {
            orderDetail.setFault(StringUtils.join(faultList, "；"));
        }

        // 设置原价
/*        if (orderProduct.getPrice() != null) {
            order.setOriginalAmount(orderProduct.getPrice() * orderProduct.getNumber());
        }*/

        // 渠道预付全款的，如果渠道预付款超过了工单原价，清空空单原价、默认服务项、工程师收款金额
        if (order.getChannelPrepayAmount() != null && order.getChannelPrepayAmount() > 0
                && Objects.equals(order.getChannelPrepayStatus(), PayConsts.PAY_STATUS_DONE)
                && order.getOriginalAmount() != null) {
            if (order.getOriginalAmount().intValue() < order.getChannelPrepayAmount().intValue()) {
                order.setOriginalAmount(null);
                orderDTO.setOrderServiceItemList(null);
            }
        }

        // 服务分类
        orderDetail.setServCategId(omsProductDTO.getServCategId());
        orderDetail.setServCategName(product.getServCategName());
        orderDetail.setCategOneId(product.getCategOneId());
        orderDetail.setCategId(product.getCategId());
        orderDetail.setProductId(product.getProductId());
        orderDetail.setProductInfo(String.format("%s-%s*%s", StringUtils.defaultString(orderProduct.getBrandName()), omsProductDTO.getProductName(), orderProduct.getNumber()));
        // 产品分组
        orderDetail.setProductGroupId(product.getProductGroupId());
        orderDetail.setProductGroupName(product.getProductGroupName());
        // 冗余到工单
        orderWork.setServCategId(orderDetail.getServCategId());
        orderWork.setShowServCategName(showProduct.getServCategName());
        orderWork.setShowProductGroupId(showProduct.getProductGroupId());
        orderWork.setShowProductGroupName(showProduct.getProductGroupName());

        if (NumberUtil.isNotNullOrZero(product.getCategId())) {
            // 后台产品分组
            logger.info("servAssCategoryListRemoteService#getProductGroupByCategId 查询产品分组 入参：servCateg={}, categTwoId={}", omsProductDTO.getServCategId(), product.getCategId());
            CategProductGroupQuery categProductGroupQuery = new CategProductGroupQuery();
            categProductGroupQuery.setBizType(orderWork.getBizType());
            categProductGroupQuery.setServCategId(omsProductDTO.getServCategId());
            categProductGroupQuery.setCategId(product.getCategId());
            categProductGroupQuery.setShowType(BaseProductConsts.ERP_SHOW_TYPE);
            ResponseDTO<CategProductGroupDRO> categoryProductGroupDROResponseDTO = categServProductListRemoteService.getBasisProductGroupByQuery(categProductGroupQuery);
            logger.info("servAssCategoryListRemoteService#getProductGroupByCategId 查询产品分组 出参：【{}】", categoryProductGroupDROResponseDTO);
            CategProductGroupDRO categorySimpleProductGroupDRO = categoryProductGroupDROResponseDTO.getData();
            if (categorySimpleProductGroupDRO != null) {
                orderWork.setServProductGroupId(categorySimpleProductGroupDRO.getGroupId());
                orderWork.setServProductGroupName(categorySimpleProductGroupDRO.getName());
                orderWork.setBizLine(categorySimpleProductGroupDRO.getBizLine());
            }
        } else if (NumberUtil.isNotNullOrZero(showProduct.getCategId())) {
            // 前台产品分组
            logger.info("servAssCategoryListRemoteService#getProductGroupByShowCategId 查询产品分组 入参：servCateg={}, categTwoId={}", omsProductDTO.getServCategId(), showProduct.getCategId());
            CategProductGroupQuery categProductGroupQuery = new CategProductGroupQuery();
            categProductGroupQuery.setBizType(orderWork.getBizType());
            categProductGroupQuery.setServCategId(omsProductDTO.getServCategId());
            categProductGroupQuery.setCategId(showProduct.getCategId());
            categProductGroupQuery.setShowType(BaseProductConsts.EC_SHOW_TYPE);
            ResponseDTO<CategProductGroupDRO> responseDTO = categServProductListRemoteService.getBasisProductGroupByQuery(categProductGroupQuery);
            logger.info("servAssCategoryListRemoteService#getProductGroupByShowCategId 查询产品分组 出参：【{}】", responseDTO);
            CategProductGroupDRO categorySimpleProductGroupDRO = responseDTO.getData();
            if (categorySimpleProductGroupDRO != null) {
                orderWork.setServProductGroupId(categorySimpleProductGroupDRO.getGroupId());
                orderWork.setServProductGroupName(categorySimpleProductGroupDRO.getName());
                orderWork.setBizLine(categorySimpleProductGroupDRO.getBizLine());
            }
        }

    }

/*
    private OrderDiscount receiptConsume(OrderDTO orderDTO, OrderDiscount orderDiscount) {
        OrderWork orderWork = orderDTO.getOrderWork();
        OrderProduct orderProduct = orderDTO.getOrderProductList().get(0);

        // 会员权益是否包含限免权益,若包含则不能使用优惠券。
        Long orderId = orderWork.getOrderId();
        OrderMember orderMember = orderMemberService.findMemberByKey(orderId);
        logger.debug("{} 开始使用优惠券了22222：{}", orderId, JSON.toJSONString(orderMember));
        if(Objects.nonNull(orderMember) && Objects.equals(orderMember.getEquityType(), MemberConsts.EQUITY_FREE)){
            logger.info("#oms#addorder#coupon 会员单已使用限免权益，无法与优惠券叠加：orderId:{}", orderId);
            return null;
        }

        CoupConsumeDIO coupConsumeDIO = new CoupConsumeDIO();
        coupConsumeDIO.setAmount(orderWork.getOriginalAmount());
        coupConsumeDIO.setChannelId(orderWork.getChannelId());
        coupConsumeDIO.setCityId(orderWork.getCityId());
        coupConsumeDIO.setCode(orderDiscount.getRemark());
        coupConsumeDIO.setOrderId(orderWork.getOrderId());
        coupConsumeDIO.setUserId(orderWork.getUserId());
        coupConsumeDIO.setProductId(orderWork.getShowProductId());

        logger.info("#oms#addorder#coupon 使用优惠券接口入参：{}",  JSON.toJSONString(coupConsumeDIO));
        com.zmn.common.dto.ResponseDTO<CoupConsumeDRO> consumeDRO = coupRemoteService.receiptConsume(coupConsumeDIO);
        logger.info("#oms#addorder#coupon 使用优惠券接口出参：{}", JSON.toJSONString(consumeDRO));
        if (!consumeDRO.getStatusBool() || consumeDRO.getData() == null) {
            logger.info("#oms#addorder#coupon 使用优惠券接口出错：{}", JSON.toJSONString(consumeDRO));
            return null;
        }

        CoupConsumeDRO data = consumeDRO.getData();

        // 优惠类型
        Integer preferentialType = data.getPreferentialType();
        // 优惠值
        Integer preferentialValue = data.getPreferentialValue();

        String couponSourceStr = JSON.toJSONString(data);
        JSONObject couponSourceObj = JSON.parseObject(couponSourceStr);

        // 面值金额
        int discountAmount = 0;
        // 优惠类型
        int discountType = OrderConsts.ORDER_DISCOUNT_TYPE_LIMIT_FREE;

        // 转换优惠类型
        if (Objects.equals(CoupConsts.PREFERENTIAL_TYPE_DISCOUNT, preferentialType)) {
            OrderShop orderShop = orderDTO.getOrderShop();
            if (orderShop != null) {
                // 店铺下单，不重新计算优惠
                discountAmount = orderDiscount.getAmount();
                discountType = OrderConsts.ORDER_DISCOUNT_TYPE_DISCOUNT;
                //couponSourceObj.put("discountValue", orderDiscount.getAmount());
            } else {
                // 重新计算优惠
                double discountValue = MathUtil.div(100 - preferentialValue, 100, 2);
                discountAmount = (int) MathUtil.mul(orderWork.getOriginalAmount(), discountValue);
                couponSourceObj.put("discountValue", discountValue);
                discountType = OrderConsts.ORDER_DISCOUNT_TYPE_DISCOUNT;
            }
        } else if (Objects.equals(CoupConsts.PREFERENTIAL_TYPE_REDUCE, preferentialType)) {
            // 立减
            discountAmount = preferentialValue;
        }

        orderDiscount.setAmount(discountAmount);
        orderDiscount.setType(discountType);
        orderDiscount.setSourceId(data.getBatchId());
        orderDiscount.setSourceData(couponSourceObj.toJSONString());
        return orderDiscount;
    }*/

    /**
     * 处理产品
     *
     * @param showProductId 前端产品
     * @param productId     后端产品
     */
    private OmsProductDTO processProduct(OrderWork orderWork, Integer showProductId, Integer productId, Integer brandId) throws OmsBaseException {
        if (NumberUtil.isNullOrZero(showProductId) && NumberUtil.isNullOrZero(productId)) {
            throw new OmsBaseException("产品不存在");
        }

        OmsProductDTO omsProductDTO = new OmsProductDTO();

        ProductBaseDRO productBaseDRO = null;
        Integer realProductId = null;
        boolean isShowProduct = false;

        // 有后端产品ID，通过后端产品ID查找
        if (!NumberUtil.isNullOrZero(productId)) {
            ProductBaseQuery productDIO = new ProductBaseQuery();
            productDIO.setProductId(productId);
            ResponseDTO<List<ProductBaseDRO>> productDROResp = productForeignListRemoteService.listBaseDROByQuery(productDIO);
            List<ProductBaseDRO> productDROS = productDROResp.getData();
            if (CollectionUtil.isNotNullOrEmpty(productDROS)) {
                productBaseDRO = productDROS.get(0);
                realProductId = productId;
                isShowProduct = Objects.equals(GlobalConsts.YES, productBaseDRO.getShowType());
            }
        }
        // 没有后端产品ID，使用前端产品ID查找
        if (productBaseDRO == null) {
            ProductBaseQuery productDIO = new ProductBaseQuery();
            productDIO.setStatus(GlobalConsts.YES);
            productDIO.setProductId(showProductId);
            logger.info("前端产品查后端产品--req1--->productDIO={}", productDIO);
            ResponseDTO<List<ProductBaseDRO>> productDROResp = productForeignListRemoteService.listBaseDROByQuery(productDIO);
            logger.info("前端产品查后端产品--req1--->productDROResp={}", productDROResp);
            List<ProductBaseDRO> productDROS = productDROResp.getData();
            if (CollectionUtil.isNotNullOrEmpty(productDROS)) {
                productBaseDRO = productDROS.get(0);
                realProductId = showProductId;
                isShowProduct = Objects.equals(GlobalConsts.YES, productBaseDRO.getShowType());
            }
        }
        if (productBaseDRO == null) {
            throw new OmsBaseException(String.format("未找到对应的产品 productId=[%d], showProductId=[%d]",
                    productId, showProductId));
        }

        omsProductDTO.setProductName(productBaseDRO.getProductName());
        omsProductDTO.setServCategId(productBaseDRO.getServCategId());

        // 前端产品查后端产品
        if (isShowProduct) {
            DefaultEcProductQuery defaultEcProductQuery = new DefaultEcProductQuery();
            defaultEcProductQuery.setProductIdList(Lists.newArrayList(realProductId));
            defaultEcProductQuery.setShowType(BaseProductConsts.ERP_SHOW_TYPE);
            defaultEcProductQuery.setStatus(GlobalConsts.YES);
            logger.info("前端产品查后端产品--req2--->defaultEcProductQuery={}", defaultEcProductQuery);
            ResponseDTO<List<ProductBaseDRO>> listResponseDTO = productForeignListRemoteService.listEcErpProductByQuery(defaultEcProductQuery);
            logger.info("前端产品查后端产品--res2--->listResponseDTO={}", listResponseDTO);
            List<ProductBaseDRO> list = listResponseDTO.getData();
            if (CollectionUtils.isEmpty(list)) {
                throw new OmsBaseException("产品数据配置有误，[" + realProductId + "]没有映射后端产品或已禁用");
            }
            ProductBaseDRO product = list.get(0);
            // 查询前台产品对应后台产品
            BackProductPriceQueryDTO backProductPriceQueryDTO = BackProductPriceQueryDTO
                    .builder()
                    .showProductId(realProductId)
                    .bizType(orderWork.getBizType())
                    .brandId(brandId)
                    .channelId(orderWork.getChannelId())
                    .cityId(orderWork.getCityId())
                    .platWork(orderWork.getPlatWork())
                    .build();
            BackProductPriceResultDTO backProductPriceResultDTO = servItemBService.queryBackProductPrice(backProductPriceQueryDTO);

            if (Objects.nonNull(backProductPriceResultDTO)) {
                ProductBaseQuery productDIO = new ProductBaseQuery();
                productDIO.setStatus(GlobalConsts.YES);
                productDIO.setProductId(backProductPriceResultDTO.getProductId());
                logger.info("查询产品信息--req1--->productDIO={}", productDIO);
                ResponseDTO<List<ProductBaseDRO>> productDROResp = productForeignListRemoteService.listBaseDROByQuery(productDIO);
                logger.info("查询产品信息--req1--->productDROResp={}", productDROResp);
                if (CollectionUtil.isNullOrEmpty(productDROResp.getData())) {
                    throw new OmsBaseException(String.format("未找到对应的产品 productId=[%d]",
                            backProductPriceResultDTO.getProductId()));
                }
                ProductBaseDRO backProductBase = productDROResp.getData().get(0);
                omsProductDTO.setProductName(backProductBase.getProductName());
                omsProductDTO.setServCategId(backProductBase.getServCategId());
                omsProductDTO.setProduct(this.droToServProductDTO(backProductBase));
            } else {
                ServProductDTO emptyProduct = ServProductDTO.builder()
                        .servCategName(product.getServCategName())
                        .categId(product.getCategId())
                        .categName(product.getCategName())
                        .categOneId(product.getCategOneId())
                        .categOneName(product.getCategOneName())
                        .productId(0)
                        .productName("")
                        .productUnit("")
                        .productGroupId(0)
                        .productGroupName("").build();
                omsProductDTO.setProduct(emptyProduct);
            }
            omsProductDTO.setShowProduct(this.droToServProductDTO(productBaseDRO));
        } else {
            // 后端产品查前端产品
            DefaultEcProductQuery defaultEcProductQuery = new DefaultEcProductQuery();
            defaultEcProductQuery.setProductIdList(Lists.newArrayList(realProductId));
            defaultEcProductQuery.setShowType(BaseProductConsts.EC_SHOW_TYPE);
            logger.info("productForeignListRemoteService.listEcErpProductByQuery defaultEcProductQuery={}", defaultEcProductQuery);
            ResponseDTO<List<ProductBaseDRO>> listResponseDTO = productForeignListRemoteService.listEcErpProductByQuery(defaultEcProductQuery);
            logger.info("productForeignListRemoteService.listEcErpProductByQuery listResponseDTO={}", listResponseDTO);
            List<ProductBaseDRO> list = listResponseDTO.getData();
            if (CollectionUtils.isEmpty(list)) {
                throw new OmsBaseException("产品数据配置有误，[" + realProductId + "]没有映射前端产品");
            }

            omsProductDTO.setProduct(this.droToServProductDTO(productBaseDRO));
            omsProductDTO.setShowProduct(this.droToServProductDTO(list.get(0)));
        }

        logger.info("产品信息 OmsProductDTO=[{}]", JSON.toJSONString(omsProductDTO));
        return omsProductDTO;
    }

    private ServProductDTO droToServProductDTO(ProductBaseDRO productBaseDRO) {
        ServProductDTO servProductDTO = BeanMapper.map(productBaseDRO, ServProductDTO.class);
        servProductDTO.setProductName(productBaseDRO.getProductName());
        servProductDTO.setProductUnit(productBaseDRO.getUnit());
        servProductDTO.setProductGroupId(productBaseDRO.getFicoCategId());
        servProductDTO.setProductGroupName(productBaseDRO.getFicoCategName());
        servProductDTO.setTariffName(productBaseDRO.getTariffName());
        return servProductDTO;
    }

    /**
     * 查询用户信息
     */
    @Override
    public OrderUserDetailDTO getUserInfo(Integer userType, Long userId){

        OrderUserDetailDTO orderUserDetailDTO = new OrderUserDetailDTO();

        try {
            // uuc 查询个人用户信息
            ResponseDTO<UserDetailDRO> userResponseDTO = userListRemoteService.getUserDetailById(userId, false);
            logger.info("uuc查询用户信息接口出参：{}", JSONObject.toJSONString(userResponseDTO));
            if (userResponseDTO.getData() != null) {
                orderUserDetailDTO = BeanMapper.map(userResponseDTO.getData(), OrderUserDetailDTO.class);
                orderUserDetailDTO.setUserName(userResponseDTO.getData().getNickName());
            }
        } catch (Exception ex) {
            logger.warn("查询用户信息失败[userListRemoteService.getUserDetailById]，用户ID：[{}]", userId);
        }


        if (Objects.equals(userType, UserConsts.USER_TYPE_COMPANY)) {
            return orderUserDetailDTO;
        }

        try {
            ResponseDTO<List<UserAddrDRO>> addrResponseDTO = userAddrListRemoteService.listAddressByUserId(userId);
            if (CollectionUtil.isNotNullOrEmpty(addrResponseDTO.getData())) {
                UserAddrDRO userAddrDRO = addrResponseDTO.getData().stream().filter(e -> Objects.equals(e.getStatus(), GlobalConsts.YES)).collect(Collectors.toList()).get(0);
                orderUserDetailDTO.setProvinceId(userAddrDRO.getProvinceId());
                orderUserDetailDTO.setCityId(userAddrDRO.getCityId());
                orderUserDetailDTO.setCountryId(userAddrDRO.getCountryId());
                orderUserDetailDTO.setStreet(userAddrDRO.getStreet());
                orderUserDetailDTO.setAddress(userAddrDRO.getAddress());
                orderUserDetailDTO.setLatitude(userAddrDRO.getLatitude());
                orderUserDetailDTO.setLongitude(userAddrDRO.getLongitude());
            }
        } catch (Exception ex) {
            logger.warn("查询用户信息失败[userAddrListRemoteService.listAddressByUserId]，用户ID：[{}]", userId);
        }
        return orderUserDetailDTO;
    }

    /**
     * 根据手机号查询用户信息
     */
    @Override
    public List<UserBaseDRO> getUserInfoByMobile(List<String> mobiles) {
        List<UserBaseDRO> userBaseDROS = Lists.newArrayList();

        // uuc 查询用户信息
        for (String mobile : mobiles) {
            logger.info("根据手机号获取用户信息 入参：{}", mobile);
            ResponseDTO<List<UserBaseDRO>>  userResponseDTO = userListRemoteService.listUserByMobile(mobile, false);
            logger.info("根据手机号获取用户信息 出参：{}", JSON.toJSONString(userResponseDTO));
            if (CollectionUtil.isNotNullOrEmpty(userResponseDTO.getData())) {
                List<UserBaseDRO> tempUserBaseDROS = userResponseDTO.getData().stream().filter(e -> Objects.equals(e.getStatus(), GlobalConsts.YES)).collect(Collectors.toList());
                userBaseDROS.addAll(tempUserBaseDROS);
            }
        }

        return userBaseDROS;
    }

    /**
     * vvip
     *
     * @param orderDTO
     */
    private void processVVIP(OrderDTO orderDTO) {
        Order order = orderDTO.getOrder();
        OrderDetail orderDetail = orderDTO.getOrderDetail();

        // 查询是否为要客
        if (NumberUtil.isNotNullOrZero(order.getUserId()) && !Objects.equals(orderDetail.getVvip(), GlobalConsts.YES)) {
            OrderUserDetailDTO userInfo = this.getUserInfo(orderDetail.getUserType(), order.getUserId());
            orderDetail.setVvip(Objects.equals(GlobalConsts.YES, userInfo.getVvip()) ? GlobalConsts.YES : GlobalConsts.NO);
        }

        if ((StringUtils.isNotBlank(orderDetail.getTelephone())
                || StringUtils.isNotBlank(orderDetail.getTelephone2())
                || StringUtils.isNotBlank(orderDetail.getTelephone3())) && !Objects.equals(orderDetail.getVvip(), GlobalConsts.YES)) {

            List<String> mobiles = Lists.newArrayList(orderDetail.getTelephone());
            if (StringUtils.isNotBlank(orderDetail.getTelephone2())) {
                mobiles.add(orderDetail.getTelephone2());
            }
            if (StringUtils.isNotBlank(orderDetail.getTelephone3())) {
                mobiles.add(orderDetail.getTelephone3());
            }
            List<UserBaseDRO> userBaseDROS = this.getUserInfoByMobile(mobiles);

            Boolean isVVIPByMobile = userBaseDROS.stream().anyMatch(user -> {
                return Objects.equals(user.getVvip(), GlobalConsts.YES);
            });
            orderDetail.setVvip(isVVIPByMobile ? GlobalConsts.YES : GlobalConsts.NO);
        }
    }

    /**
     * 处理订单标签
     *
     * @param orderDTO
     */
    private void processOrderTag(OrderDTO orderDTO) {

        /*try {
            // 处理优质订单标签id
            this.processHighQualityTag(orderDTO);
        } catch (Exception e) {
            logger.error("[{}]处理优质订单标签报错：【{}】", orderDTO.getOrderId(), e.getMessage());
        }*/

        if (CollectionUtil.isNullOrEmpty(orderDTO.getOrderTagIdList())) {
            return;
        }

        OrderWork orderWork = orderDTO.getOrderWork();
        ConfOrderTagQuery query = ConfOrderTagQuery.builder().ids(orderDTO.getOrderTagIdList()).build();
        List<ConfOrderTag> confOrderTagList = confOrderTagService.listByQuery(query);
        Map<Integer, ConfOrderTag> confMap = confOrderTagList.stream().collect(Collectors.toMap(ConfOrderTag::getId, e -> e, (v1, v2) -> v1));

        List<OrderTag> tagList = Lists.newArrayList();
        orderDTO.getOrderTagIdList().forEach(orderTagId -> {
            ConfOrderTag conf = confMap.get(orderTagId);
            if (Objects.isNull(conf)) {
                return;
            }

            OrderTag tag = new OrderTag();
            tag.setOrderId(orderWork.getOrderId());
            tag.setWorkId(orderWork.getWorkId());
            tag.setTagType(OrderTagConsts.ORDER_TAG_USER_SYSTEM);
            tag.setTagId(conf.getId());
            tag.setTagName(conf.getTagName());
            tag.setCategoryIds(conf.getCategoryIds());
            tag.setCreater(Optional.ofNullable(orderDTO.getOperator()).orElse("系统"));
            tag.setUpdater(Optional.ofNullable(orderDTO.getOperator()).orElse("系统"));
            tagList.add(tag);
        });

        orderDTO.setOrderTagList(tagList);
    }

    /**
     * 处理优质订单标签
     * @param orderDTO
     */
    private void processHighQualityTag(OrderDTO orderDTO) {

        // 获取优质订单渠道配置
        List<TagsDRO> list = baseCodeService.listBaseCodeMap(com.zmn.consts.GlobalConsts.PLAT_MARK_ZMN, OrderConsts.BASE_CODE_MAP_ONE_TYPE_HIGH_QUALITY, orderDTO.getOrderWork().getChannelId(), null);

        // 已录入
        if (Objects.isNull(orderDTO.getDbOrderWork())) {
            if (CollectionUtil.isNullOrEmpty(list)) {
                return;
            }
            // 添加tagId
            this.addOrderTagIdList(orderDTO, OrderTagConsts.TAG_ID_HIGH_QUALITY);
            return;
        }

        // 已修改
        List<OrderTag> orderTagList = orderTagService.listOrderTagByOrderIdAndTagId(orderDTO.getOrderId(), OrderTagConsts.TAG_ID_HIGH_QUALITY);
        if (CollectionUtil.isNullOrEmpty(orderTagList)) {
            if (CollectionUtil.isNullOrEmpty(list)) {
                return;
            }
            // 添加tagId
            this.addOrderTagIdList(orderDTO, OrderTagConsts.TAG_ID_HIGH_QUALITY);
            return;
        }

        // 如果订单标签不为空，配置为空，择删除标签
        if (CollectionUtil.isNullOrEmpty(list)) {
            OrderTagDelDTO orderTagDelDTO = new OrderTagDelDTO();
            orderTagDelDTO.setOrderId(orderDTO.getDbOrderWork().getOrderId());
            orderTagDelDTO.setWorkId(orderDTO.getDbOrderWork().getWorkId());
            orderTagDelDTO.setOrderTagIdList(Lists.newArrayList(OrderTagConsts.TAG_ID_HIGH_QUALITY));
            orderTagService.deleteOrderTagByTagIdList(orderTagDelDTO);
        }
    }

    /**
     * tagId添加到集合
     * @param orderDTO
     * @param tagId
     */
    private void addOrderTagIdList(OrderDTO orderDTO, Integer tagId) {
        // list为空创建一个新的list
        if (CollectionUtil.isNullOrEmpty(orderDTO.getOrderTagIdList())) {
            orderDTO.setOrderTagIdList(Lists.newArrayList(tagId));
            return;
        }
        // list不为空直接添加
        orderDTO.getOrderTagIdList().add(tagId);
    }

    private OrderServiceItem getServiceItemWithPhenId(OrderDTO orderDTO) {
        OrderFinalPriceQuotation quotation = orderDTO.getOrderFinalPriceQuotation();
        if (Objects.isNull(quotation)) {
            return null;
        }
        Integer phenId = quotation.getPhenId();
        if (Objects.isNull(phenId)) {
            return null;
        }

        OrderWork orderWork = orderDTO.getOrderWork();
        OrderProduct orderProduct = orderDTO.getOrderProductList().get(0);

        FixedErpProductQuery2 productQuery = FixedErpProductQuery2.builder()
                .bizType(orderWork.getBizType())
                .channelId(orderWork.getChannelId())
                .cityId(orderWork.getCityId())
                .ecProductId(orderWork.getShowProductId())
                .phenomenonId(phenId)
                .categId(orderProduct.getCategId())
                .brandId(orderProduct.getBrandId())
                .flag(true)
                .build();
        logger.info("[{}]故障现象查询后台产品 入参：{}", "下单", JSON.toJSONString(productQuery));
        ResponseDTO<List<FixedErpProductDRO>> responseDTO = fixedFlowRemoteService.listErpProductFilterPhenoByQuery(productQuery);
        logger.info("[{}]故障现象查询后台产品 出参：{}", "下单", JSON.toJSONString(responseDTO));
        if (!responseDTO.isSuccess() || CollectionUtil.isNullOrEmpty(responseDTO.getData())) {
            logger.info("获取故障现象失败: {}", responseDTO.getMessage());
            return null;
        }

        // 取价格最低的服务项
        Optional<ItemSimpleDRO> itemOptional = responseDTO.getData()
                .stream()
                .filter(product -> CollectionUtil.isNotNullOrEmpty(product.getItemDROList()))
                .flatMap(product -> product.getItemDROList().stream())
                .min(Comparator.comparing(ItemSimpleDRO::getPrice));

        if (!itemOptional.isPresent()) {
            return null;
        }
        Integer itemId = itemOptional.get().getItemId();

        // 查询服务项
        ItemPriceQuery query = ItemPriceQuery
                .builder()
                .productId(NumberUtil.isNotNullOrZero(orderProduct.getProductId()) ? orderProduct.getProductId() : orderProduct.getShowProductId())
                .showType(NumberUtil.isNullOrZero(orderProduct.getProductId()) ? BaseProductConsts.EC_SHOW_TYPE : BaseProductConsts.ERP_SHOW_TYPE)
                .bizType(orderWork.getBizType())
                .brandId(orderProduct.getBrandId())
                .channelId(orderWork.getChannelId())
                .cityId(orderWork.getCityId())
                .itemList(Lists.newArrayList(itemId))
                .tariffId(orderProduct.getTariffId())
//                .itemStandard(serviceItemQueryDTO.getPriceStandard())
//                .tariffId(serviceItemQueryDTO.getTariffId())
//                .itemTypeId(serviceItemQueryDTO.getItemCategId())
                .build();
        logger.info("itemPriceRemoteService.listItemPriceByQuery itemPriceQuery={}", com.alibaba.fastjson.JSON.toJSONString(query));
        ResponseDTO<List<ItemDRO>> itemResponseDTO = itemPriceRemoteService.listItemPriceByQuery(query);
        logger.info("itemPriceRemoteService.listItemPriceByQuery responseDTO={}", com.alibaba.fastjson.JSON.toJSONString(responseDTO));
        if (!itemResponseDTO.isSuccess() || CollectionUtil.isNullOrEmpty(itemResponseDTO.getData())) {
            logger.info("获取服务项失败: {}", responseDTO.getMessage());
            return null;
        }

        // 筛选最低价服务项
        Optional<ItemDRO> itemDROOptional = itemResponseDTO.getData().stream().filter(item -> NumberUtil.isNotNullOrZero(item.getPrice())).min(Comparator.comparing(ItemDRO::getPrice));
        if (!itemDROOptional.isPresent()) {
            return null;
        }
        ItemDRO itemDRO = itemDROOptional.get();
        // 处理内部结算价
        Integer internalPrice = Optional.ofNullable(itemDRO.getPriceInternalSettlement()).orElse(itemDRO.getPrice());
        Integer internalSettlementPrice = orderServiceItemBService.handleSettlementPrice(orderWork.getPlatWork(), orderWork.getChannelId(), orderWork.getBizType(), internalPrice, itemDRO.getPrice());

        // 构建默认服务项
        OrderServiceItem orderServiceItem = new OrderServiceItem();
        orderServiceItem.setOrderId(orderWork.getOrderId());
        orderServiceItem.setProductId(orderProduct.getProductId());
        orderServiceItem.setProductName(orderProduct.getProductName());
        orderServiceItem.setServItemId(itemDRO.getItemId());
        orderServiceItem.setServItemName(itemDRO.getItemName());
        orderServiceItem.setServItemGroupId(itemDRO.getCategId());
        orderServiceItem.setServItemGroupName(itemDRO.getCategName());
        orderServiceItem.setServItemCategId(itemDRO.getCategId());
        orderServiceItem.setNumber(1);
        orderServiceItem.setItemPrice(itemDRO.getPrice());
        orderServiceItem.setTotalPrice(itemDRO.getPrice());
        orderServiceItem.setInternalSettlementPrice(internalSettlementPrice);
        orderServiceItem.setInternalTotalPrice(internalSettlementPrice);
        orderServiceItem.setExternalSettlementPrice(Optional.ofNullable(itemDRO.getPriceExternalSettlement()).orElse(itemDRO.getPrice()));
        orderServiceItem.setExternalTotalPrice(Optional.ofNullable(itemDRO.getPriceExternalSettlement()).orElse(itemDRO.getPrice()));
        // 故障项明细
        if (CollectionUtil.isNotNullOrEmpty(itemDRO.getItemCellList())) {
            List<OrderServiceItemCell> itemCellList = new ArrayList<>(itemDRO.getItemCellList().size());
            for (ItemCellDRO itemCell : itemDRO.getItemCellList()) {
                OrderServiceItemCell cell = new OrderServiceItemCell();
                cell.setItemCellId(itemCell.getItemCellId());
                cell.setItemCellName(itemCell.getItemCellName());
                cell.setCellPrice(itemCell.getCellPrice());
                cell.setSort(itemCell.getSort());
                itemCellList.add(cell);
            }
            orderServiceItem.setItemDetailList(itemCellList);
        }
        return orderServiceItem;
    }

}